import os
import pandas as pd
import re
from src.common.files import Files
from src import mysql_db as db
from src.model.model import SyncStatus
from src.utils import get_upload_path, get_YmdHMS


def compare_exec(uuid, file1, file2, columns, output_file):
    # 分割对比字段，包括中文逗号和英文逗号
    index = re.split(',|，', columns.replace(' ', ''))
    # 对比数据
    result1_2, result2_1, result12 = data_compare(Files.get_content(file1, index), Files.get_content(file2, index))
    # 写入结果
    Files.write_file_sheet(output_file, result1_2, 'file1-file2')
    Files.write_file_sheet(output_file, result2_1, 'file2-file1')
    Files.write_file_sheet(output_file, result12, 'file1+file2')

    # 更新数据库处理状态
    db.session.query(SyncStatus).filter(SyncStatus.uuid == uuid).update({SyncStatus.status: 1, SyncStatus.update_time: get_YmdHMS()})
    db.session.commit()


def data_compare(compare1, compare2):
    # 返回compare1-compare2的差集数据
    result1_2 = pd.concat([compare1, compare2, compare2]).drop_duplicates(keep=False)
    result1_2.index.name = '索引'

    # 返回compare2-compare1的差集数据
    result2_1 = pd.concat([compare1, compare1, compare2]).drop_duplicates(keep=False)
    result2_1.index.name = '索引'

    # 返回compare1和compare2不一致的差集数据
    result12 = pd.concat([compare1, compare2]).drop_duplicates(keep=False)
    result12.index.name = '索引'

    return result1_2, result2_1, result12

